# @Version        : 1.0
# @Update Time    : 2025/10/20 19:11
# @File           : auth.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息

from typing import Optional

from fastapi import Request, Security

from authx.dependencies.helpers import ensure_login
from authx.dependencies.oauth2 import oauth2_required


class RequireLogin:
    def __init__(self, user_type: str = "login"):
        self.user_type = user_type.strip() or "login"

    async def __call__(
        self, request: Request, token: Optional[str] = Security(oauth2_required)
    ) -> str:
        auth_logic, login_id, _ = await ensure_login(request, self.user_type, token)
        return login_id


class OptionalLogin:
    """可选登录依赖类 - 登录用户返回ID，未登录返回None（支持多用户类型）"""

    def __init__(self, user_type: str = "login"):
        """初始化可选登录校验器

        Args:
            user_type: 用户类型，默认为 "login"
        """
        # 验证用户类型
        if isinstance(user_type, str) and user_type.strip() != "":
            self.user_type = user_type.strip()
        else:
            self.user_type = "login"

    async def __call__(
        self, request: Request, token: str = Security(oauth2_required)
    ) -> Optional[str]:
        if not token:
            return None
        _, login_id, _ = await ensure_login(request, self.user_type, token)
        return login_id
